package com.supermarket.api.common.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * redis 的操作工具类
 * @author li
 */
@Component
public class RedisOperate {

	@Autowired
	private RedisTemplate<String,String> redisTemplate;

	@Bean
	public RedisTemplate<String, String> stringSerializerRedisTemplate() {
		RedisSerializer<String> stringSerializer = new StringRedisSerializer();
		redisTemplate.setKeySerializer(stringSerializer);
		redisTemplate.setValueSerializer(stringSerializer);
		redisTemplate.setHashKeySerializer(stringSerializer);
		redisTemplate.setHashValueSerializer(stringSerializer);
		return redisTemplate;
	}


	/**
	 * 设置键
	 * @param key
	 * @param value
	 * @param expireTime
	 */
	public void  set(final String key,final String value,final long expireTime) {
		ValueOperations<String, String> ops = this.redisTemplate.opsForValue();
		ops.set(key, value, expireTime, TimeUnit.SECONDS);
	}
	
	/**
	 * 设置键
	 * @param key
	 * @param value
	 */
	public void  set(final String key,final String value) {
		ValueOperations<String, String> ops = this.redisTemplate.opsForValue();
		ops.set(key, value);
	}
	
	/**
	 * 设置键
	 * @param key
	 * @param value
	 */
	public void setMap(final String key,final Map<?, ?> value) {
		HashOperations<String, Object, Object>  ops = this.redisTemplate.opsForHash();
		ops.putAll(key, value);
	}
	
	/**
	 * 获取值
	 * @param key
	 * @return
	 */
	public String get(final String key) {
		ValueOperations<String, String> ops = this.redisTemplate.opsForValue();
		return ops.get(key);
	}
	
	/**
	 * 删除值
	 * @param key
	 * @return
	 */
	public void delete(final String key){
		this.redisTemplate.delete(key);
	}
	
	/**
	 * 删除值 模糊匹配
	 * @param keys
	 * @return
	 */
	public void deletes(final String keys){
		this.redisTemplate.delete(this.redisTemplate.keys(keys));
	}

    /**
     * 按delta递增
     * @param key
     * @param delta
     * @return
     */
    public Long incr(String key, long delta) {
        return this.redisTemplate.opsForValue().increment(key, delta);
    }

}
